package pl.edu.agh.anomalyids.launcher;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pl.edu.agh.anomalyids.launcher.util.LauncherUtils;
import pl.edu.agh.anomalyids.lerad.listener.PacketCollector;
import pl.edu.agh.anomalyids.network.Interface;
import pl.edu.agh.anomalyids.network.sniffer.Sniffer;
import pl.edu.agh.anomalyids.network.util.PacketWriter;

public class SnifferLauncher {

	private static final Logger logger = LoggerFactory
			.getLogger(SnifferLauncher.class);

	private List<Interface> interfaces;

	public static void main(String[] args) {
		if (args.length < 2) {
			System.out.println("Correct arguments: <sniffing time in seconds> <output file path>");
			logger.error("Bad arguments.");
			System.exit(-1);
		}

		SnifferLauncher launcher = new SnifferLauncher();

		launcher.interfaces = Sniffer.getInterfacesList();
		LauncherUtils.printInterfaces(launcher.interfaces);
		String input = LauncherUtils.getUserInput(logger);

		try {
			String interfaceName = launcher.interfaces.get(
					Integer.valueOf(input)).getName();

			long workTime = LauncherUtils.secondsToMiliseconds(Long
					.valueOf(args[0]));
			Sniffer sniffer = new Sniffer(interfaceName, workTime);

			String filePath = args[1];
			PacketCollector collector = new PacketCollector();
			sniffer.addPacketListener(collector);

			sniffer.start();
			sniffer.join();

			new PacketWriter(collector.getPackets()).write(filePath);
		} catch (InterruptedException e) {
			logger.error("Sniffer interrupted.", e);
		}
	}
}
